package com.efounder.form.comp;

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.efounder.builder.base.data.DataSetEvent;
import com.efounder.builder.base.data.DataSetListener;
import com.efounder.builder.base.data.EFDataSet;
import com.efounder.builder.base.data.EFRowSet;
import com.efounder.form.DMColComponent;
import com.efounder.form.DMComponent;
import com.efounder.form.DataSetComponent;
import com.efounder.form.application.util.FormAppUtil;
import com.efounder.form.base.IComponent;
import com.efounder.form.builder.IScriptObject;
import com.efounder.form.model.JSONFormModel;
import com.efounder.form.model.MDModel;
import com.efounder.form.util.FormCompUtil;
import com.efounder.frame.ViewSize;
import com.efounder.mobilecomps.R;
import com.efounder.util.AppContext;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import cn.qqtheme.framework.picker.OptionListViewPicker;

/***
 * auto by lch
 * mainrowset是为了方便提交表单的
 * mdDataSet 是主数据
 * currentrowset 是主数据当前选中的行
 */
public class FormDataSetFieldComboBox extends TextView implements IComponent,IUIComponent,DMComponent,DMColComponent,IScriptObject,DataSetListener {

	private String originalText;
	private Boolean editable = true;

	private int gap;

	private DataSetComponent dataSetComponent;//FormModel
	private String dataSetID;//FormModel的dataSetID
	private String dataSetColID;//FormModel的编号列（表单中不显示）
	private String viewDataSetColID;//FormModel名称列（表单中显示）
	private String valueDataSetColID;//暂时不用

	private MDModel mdModel;//mdModel
	private String viewDataSetID;//mdModel的dataSetID(弹出框选择框中的数据)
	private String BHDataSetColID;//mdModel的编号列（弹出框选择框中不显示）
	private String MCDataSetColID;//mdModel的名称列（弹出框选择框中显示）

	private String horizontalAlign;
	private String verticalAlign;

	private EFDataSet dataSet;

	//mainrowset是为了方便提交表单的
	private EFRowSet mainRowSet;

	//currentrowset 是主数据当前选中的行
	private EFRowSet currentRowSet;


	private IUIComponent parentComp;


	private ViewSize size = new ViewSize(0, 0);

	private Context context;
	private String imageUrl ="http://oap8mw8pg.bkt.clouddn.com/FndmI1RMqRYuwYSI2ouMu3pM4zEv";
	//private String imageUrl =" http://tupian.qqjay.com/tou3/2016/0725/cb00091099ffbf09f4861f2bbb5dd993.jpg";
	private ArrayList<String> helpStringList;


	private enum  FORMAT  {BH,MC,BHMC};

	private Map scriptObject = new HashMap();
	private Map scriptContext = new HashMap();

	public FormDataSetFieldComboBox() {
//		super(AppContext.getInstance());
//		this.context = AppContext.getInstance();
		super(AppContext.getInstance());
		this.context = AppContext.getInstance();
		this.setTextColor(Color.BLACK);
	}

	public FormDataSetFieldComboBox(Context context) {
		super(context);
		this.context = AppContext.getInstance();
	}
	public FormDataSetFieldComboBox(Context context, AttributeSet attrs) {
		super(context, attrs);
		this.context = AppContext.getInstance();
	}

	private void showToast(String msg) {
		Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
	}

	private String bh;



	private EFDataSet mdDataSet;
	public void dataChanged(EFDataSet dataSet) {
		if(dataSet.getTableName().equals(dataSetID)) {
			//formmodel
			mainRowSet = dataSet.getCurrentRowSet();
			if (mainRowSet != null) {
				bh = mainRowSet.getString(dataSetColID, "");
			}
		}else if(dataSet.getTableName().equals(viewDataSetID)) {
			//mdmodel
			if (mdModel == null) return;
			mdDataSet = mdModel.getMdmDataModel().getDataSet(viewDataSetID);
		}
		initByDataSet(mdDataSet,bh);
	}

	@Override
	public void setLayout() {
		FormCompUtil.setLayoutSize(this);
		this.setGravity(FormCompUtil.getLayoutGravity(horizontalAlign, verticalAlign));

		LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
		layoutParams.width= this.getViewSize().getWidth();
		layoutParams.height = this.getViewSize().getHeight();
		this.setLayoutParams(layoutParams);

		this.setGravity(Gravity.LEFT|Gravity.CENTER_VERTICAL);
	}

	@Override
	public void creationComplete() {
		if(imageUrl.equals("")){
			Drawable rightDrawable = getResources().getDrawable(R.drawable.icon_help_search);
			rightDrawable.setBounds(0, 0, rightDrawable.getMinimumWidth(), rightDrawable.getMinimumHeight());
			FormDataSetFieldComboBox.this.setCompoundDrawables(null,null,rightDrawable,null);
		}else {
			new DownloadImageTask().execute(imageUrl);
		}

		this.setBackgroundResource(R.drawable.ymdeditbackground);
		//this.setGravity(Gravity.CENTER);
		this.setTextColor(getResources().getColor(R.color.black));
		FormDataSetFieldComboBox.this.setText("");
		//添加点击事件
		this.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (!editable) return;
				if (helpStringList == null || helpStringList.size() == 0){
					Toast.makeText(getContext(),"没有数据权限",Toast.LENGTH_SHORT).show();
					return;
				}
				OptionListViewPicker optionPicker = new OptionListViewPicker(AppContext.getCurrentActivity(),helpStringList);
				optionPicker.setOnOptionPickListener(new OptionListViewPicker.OnOptionPickListener() {
					@Override
					public void onOptionPicked(int position, String option) {
						FormDataSetFieldComboBox.this.setText(option);
						if (mdModel == null) return;
						currentRowSet = mdModel.getMdmDataModel().getDataSet(viewDataSetID).getRowSet(position);
						mainRowSet.putObject(dataSetColID, currentRowSet.getString(BHDataSetColID, ""));
						mainRowSet.putObject(viewDataSetColID, currentRowSet.getString(MCDataSetColID, ""));
						//执行脚本
						try {
							FormAppUtil.executeCompScripts(FormDataSetFieldComboBox.this, scriptContext, "click", null);
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				});
				optionPicker.show();

			}
		});

		//if (mdModel == null) return;
		//initByDataSet(mdDataSet,"");
	}

	private void initByDataSet(EFDataSet dataSet,String bh){
		if (dataSet == null || bh== null) return;
		helpStringList  = new ArrayList<>();
		String currentValue = "";
		for(int i=0;i<dataSet.getRowCount();i++){
			EFRowSet efRowSet = dataSet.getRowSet(i);
			String key = efRowSet.getString(BHDataSetColID,"");
			String value = efRowSet.getString(MCDataSetColID ,"");
			helpStringList.add(formatValue(key,value));
			if (key.equals(bh)) {
				currentValue = formatValue(key,value);
			}
		}
//
//
//		for (int i = 0; i < dataSet.getRowSetList().size() ; i++) {
//			EFRowSet rowSet = (EFRowSet)dataSet.getRowSetList().get(i);
//			if (rowSet.getString(BHDataSetColID, null).equals(bh)) {
//				viewValue = rowSet.getString(MCDataSetColID, null);
//				break;
//			}
//		}
		setText(currentValue);

	}

	private String formatValue(String key ,String value){
		String result = "";
		switch(format) {
			case "key":
				result = key;
				break;
			case "value":
				result = value;
				break;
			case "keyvalue":
				result = key + value;
				break;
			case "valuekey":
				result = value + key;
				break;
			case "key-value":
				result = key +"-"+ value;
				break;
			case "value-key":
				result = value +"-"+ key;
				break;
		}
		return result;

	}
	public String getOriginalText() {
		return originalText;
	}

	public void setOriginalText(String originalText) {
		this.originalText = originalText;

		this.setText(originalText);
	}

	@Override
	public DataSetComponent getDataSetComponent() {
		return dataSetComponent;
	}

	@Override
	public void setDataSetComponent(DataSetComponent dsc) {
		if (dataSetComponent != null)
			dataSetComponent.removeDMComponent(this);
		dataSetComponent = dsc;
		if (dataSetComponent != null)
			dataSetComponent.insertDMComponent(this);
	}

	public void setDataSetComponent(JSONFormModel dsc) {
		if (dataSetComponent != null)
			dataSetComponent.removeDMComponent(this);
		dataSetComponent = dsc;
		if (dataSetComponent != null)
			dataSetComponent.insertDMComponent(this);
	}



	//帮助组件设置左侧图标
	private Drawable loadImageFromNetwork(String imageUrl)
	{
		Drawable drawable = null;
		try {
			// 可以在这里通过文件名来判断，是否本地有此图片
			drawable = Drawable.createFromStream(
					new URL(imageUrl).openStream(), "image.jpg");
		} catch (IOException e) {
			Log.d("test", e.getMessage());
		}
		if (drawable == null) {
			Log.d("test", "null drawable");
		} else {
			Log.d("test", "not null drawable");
		}

		return drawable ;
	}
	public String getHorizontalAlign() {
		return horizontalAlign;
	}

	public void setHorizontalAlign(String horizontalAlign) {
		this.horizontalAlign = horizontalAlign;
	}

	public String getVerticalAlign() {
		return verticalAlign;
	}

	public void setVerticalAlign(String verticalAlign) {
		this.verticalAlign = verticalAlign;
	}

	@Override
	public void setDataSetID(String dataSetID) {
		this.dataSetID = dataSetID;
	}

	@Override
	public String getDataSetColID() {
		return dataSetColID;
	}

	@Override
	public void setDataSetColID(String dataSetColID) {
		this.dataSetColID = dataSetColID;
	}

	@Override
	public String getDataSetNameColID() {
		return null;
	}

	@Override
	public void setDataSetNameColID(String value) {

	}

	@Override
	public String getInternalDataSetID() {
		return null;
	}

	@Override
	public void setInternalDataSetID(String dataSetID) {

	}



	@Override
	public Boolean getIsUserInternalDataSetID() {
		return null;
	}

	@Override
	public void setIsUserInternalDataSetID(Boolean v) {

	}

	@Override
	public String getIdentifier() {
		return null;
	}

	@Override
	public Object getPropertyMap() {
		return null;
	}

	@Override
	public void setPropertyMap(Object value) {

	}

	@Override
	public Object getProperty(String key, Object defVal) {
		return null;
	}

	@Override
	public void setProperty(String key, Object value) {

	}

	@Override
	public int getNumberPrecision() {
		return 0;
	}

	@Override
	public void seNumberPrecision(int value) {

	}

	@Override
	public String getNumberFormat() {
		return null;
	}

	@Override
	public void setNumberFormat(String numberFormat) {

	}

	@Override
	public String getColumnType() {
		return null;
	}

	@Override
	public void setColumnType(String value) {

	}

	@Override
	public String getEditorType() {
		return null;
	}

	@Override
	public void setEditorType(String value) {

	}

	@Override
	public String getDateFormat() {
		return null;
	}

	@Override
	public void setDateFormat(String dateFormat) {

	}

	@Override
	public String getFormulaOne() {
		return null;
	}

	@Override
	public void setFormulaOne(String formulaOne) {

	}

	@Override
	public String getEditMask() {
		return null;
	}

	@Override
	public void setEditMask(String editMask) {

	}

	@Override
	public String getFkeyID() {
		return null;
	}

	@Override
	public void setFkeyID(String fkey) {

	}

	@Override
	public String getRlglID() {
		return null;
	}

	@Override
	public void setRlglID(String rlglID) {

	}

	@Override
	public String getDataSetID() {
		return dataSetID;
	}

	@Override
	public void setDataSet(EFDataSet dataSet) {
		if ( this.dataSet != dataSet ) {
			if ( this.dataSet != null ) this.dataSet.removeDataSetListener(this);
			this.dataSet = dataSet;
			if ( this.dataSet != null ) this.dataSet.addDataSetListener(this);
			this.dataChanged(dataSet);
		}

	}

	@Override
	public EFDataSet getDataSet() {
		return dataSet;
	}

	@Override
	public EFRowSet getMainRowSet() {
		return mainRowSet;
	}

	@Override
	public void dataSetChanged(DataSetEvent event) {
		dataChanged(event.getDataSet());
	}

	@Override
	public String getID() {
		return id;
	}

	@Override
	public void setID(String id) {
		this.id = id;
	}

	@Override
	public int getGap() {
		return gap;
	}

	@Override
	public void setGap(int gap) {
		this.gap = gap;
	}

	@Override
	public void setWidth(int width) {
		this.width = width;
	}

	@Override
	public void setHeight(int height) {
		this.height = height;
	}

	@Override
	public int getPercentWidth() {
		return percentWidth;
	}

	@Override
	public void setPercentWidth(int percentW) {
		percentWidth = percentW;
	}

	@Override
	public int getPercentHeight() {
		return percentHeight;
	}

	@Override
	public void setPercentHeight(int percentH) {
		percentHeight = percentH;
	}

	@Override
	public ViewSize getViewSize() {
		return size;
	}

	@Override
	public void setViewSize(ViewSize size) {
		this.size = size;
	}

	@Override
	public void setCompWidth(int width) {
		this.width = width;
	}

	@Override
	public int getCompWidth(){
		return this.width;
	}

	@Override
	public void setCompHeight(int height) {
		this.height = height;
	}

	@Override
	public int getCompHeight() {
		return this.height;
	}

	public MDModel getMdModel() {
		return mdModel;
	}

	public void setMdModel(MDModel mdModel) {
		this.mdModel = mdModel;
		mdModel.insertDMComponent(this);
	}

	@Override
	public String getValueDataSetColID() {
		return valueDataSetColID;
	}

	@Override
	public void setValueDataSetColID(String valueDataSetColID) {
		this.valueDataSetColID = valueDataSetColID;
	}

	@Override
	public String getViewDataSetColID() {
		return viewDataSetColID;
	}

	@Override
	public void setViewDataSetColID(String viewDataSetColID) {
		this.viewDataSetColID = viewDataSetColID;
	}

	@Override
	public String getViewDataSetID() {
		return viewDataSetID;
	}

	@Override
	public void setViewDataSetID(String viewDataSetID) {
		this.viewDataSetID = viewDataSetID;
	}

	private String id;
	private int x = 0;
	private int y = 0;
	private boolean enabled;
	private String toolTip;
	private boolean visible;
	private int width;
	private int height;
	private int percentWidth;
	private int percentHeight;



	private String format = "value";//key ; keyvalue ; value;
	public void setId(String id) {
		this.id = id;
	}
	public void setX(int x) {
		this.x = x;
	}
	public void setY(int y) {
		this.y = y;
	}
	public Boolean getEnabled() {
		return enabled;
	}
	public String getToolTip(String a) {
		return toolTip;
	}
	public Boolean getVisible() {
		return visible;
	}
	public void setVisible(Boolean visible) {
		this.visible = visible;
	}
	public void setEnabled(Boolean enabled) {
		this.enabled = enabled;
		super.setEnabled(enabled);
	}

	public void setToolTip(String toolTip) {
		this.toolTip = toolTip;
	}
	//不可输入状态时，确定是否点击整个组件下拉 true->点击整个组件下拉
	private boolean isClickInputOpenList = false;
	public boolean isClickInputOpenList() {
		return isClickInputOpenList;
	}
	@Override
	public IUIComponent getParentComp() {
		return parentComp;
	}
	@Override
	public void setParentComp(IUIComponent comp) {
		parentComp = comp;
	}
	private class DownloadImageTask extends AsyncTask<String, Void, Drawable>
	{
		protected Drawable doInBackground(String... urls) {
			Drawable drawable = loadImageFromNetwork(urls[0]);
			return drawable;
		}
		protected void onPostExecute(Drawable result) {
			if (result == null) return;
			//  mImageView.setImageDrawable(result);
			final Drawable rightDrawable = getResources().getDrawable(R.drawable.icon_help_search);
			rightDrawable.setBounds(0, 0, rightDrawable.getMinimumWidth(), rightDrawable.getMinimumHeight());
			result.setBounds(0, 0, rightDrawable.getMinimumWidth(), rightDrawable.getMinimumHeight());
			// Drawable leftDrawable = getResources().getDrawable(R.drawable.icon_search);
			//leftDrawable.setBounds(0, 0, rightDrawable.getMinimumWidth(), rightDrawable.getMinimumHeight());
			FormDataSetFieldComboBox.this.setCompoundDrawables(result,null,rightDrawable,null);
//            FormDataSetFieldComboBox.this.post(new Runnable() {
//                @Override
//                public void run() {
//
//                }
//            });
		}
	}
	public EFDataSet getMdDataSet() {
		return mdDataSet;
	}

	public void setMdDataSet(EFDataSet mdDataSet) {
		this.mdDataSet = mdDataSet;
	}
	public EFRowSet getCurrentRowSet() {
		return currentRowSet;
	}

	public void setCurrentRowSet(EFRowSet currentRowSet) {
		this.currentRowSet = currentRowSet;
	}
	/************************js相关*********************/
	public Boolean getEditable() {
		return editable;
	}

	public void setEditable(Boolean editable) {
		this.editable = editable;
	}

	@Override
	public CharSequence getText() {
		return super.getText();
	}
	public String getFormat() {
		return format;
	}

	public void setFormat(String format) {
		this.format = format;
	}

	@Override
	public Map getScriptObject() {
		return scriptObject;
	}

	@Override
	public void setScriptObject(Map map) {
		this.scriptObject = map;
	}

	@Override
	public String getEventScript(String key) {
		return (String) scriptObject.get(key);
	}

	@Override
	public void setEventScript(String key, String script) {
		scriptObject.put(key, script);
	}

	@Override
	public Map getScriptContext() {
		return scriptContext;
	}

	@Override
	public void setScriptContext(Map context) {
		scriptContext = context;
	}
	/************************js相关*********************/
}
